/**********************************************************/
/* Goblin Defense - A tower defense game for Wii Homebrew */
/* Copyright (C) 2009 Ricardo Bueno Cordeiro              */
/* Licensed under de GNU General Public License v2.0      */
/*   See license_gplv2.txt for detalis                    */
/**********************************************************/

#include <gccore.h>
#include "random.h"

#include "draw.h"
#include "path.h"

void path_advance_1_step(PATH *path, PATH_POS *pos) {
	pos->step++;
	
	if (pos->step < path->points[pos->point].segs[pos->segment].steps)
		return;
	
	pos->step = 0;
	pos->point = path->points[pos->point].segs[pos->segment].dest_point;

	PATH_POINT &current_point = path->points[pos->point];
	
	int weight = 0;
	for(int i = 0; i < current_point.num_segs; i++)
		weight += current_point.segs[i].weight;

	weight = generate() % weight;
	pos->segment = 0;

	for(int i = 0; i < current_point.num_segs; i++) {
		weight -= current_point.segs[i].weight;
		if (weight < 0) {
			pos->segment = i;
			break;
		}
	}
}

void path_get_coordinates(PATH *path, PATH_POS *pos, f32 *x, f32 *y) {
	PATH_POINT &start_point = path->points[pos->point];
	PATH_POINT &end_point = path->points[start_point.segs[pos->segment].dest_point];
	f32 dist = ((f32)pos->step) / (f32)start_point.segs[pos->segment].steps;

	*x = (((f32)start_point.x) * (1.0 - dist) + ((f32)end_point.x) * dist);
	*y = (((f32)start_point.y) * (1.0 - dist) + ((f32)end_point.y) * dist);
}

void path_new_pos(PATH *path, PATH_POS *pos) {
	pos->point = path->spawn_points[generate() % path->num_spawn_points];
	pos->segment = 0;
	pos->step = 0;
}
